package com.xwj.back.service.impl;

import com.xwj.back.mapper.RoleMapper;
import com.xwj.back.pojo.Menu;
import com.xwj.back.pojo.Role;
import com.xwj.back.service.MenuService;
import com.xwj.back.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuService menuService;

    @Override
    public List<Role> getRoleAll(String role) {
        if("ROLE_ADMIN".equals(role))
            return roleMapper.selectList(null);
        return null;
    }

    @Override
    public Map<String, String> addRole(Map<String, String> data) {
        String role = data.get("role");
        Map<String, String> map = new HashMap<>();
        if(!"ROLE_ADMIN".equals(role)){
            map.put("message","error");
            return map;
        }
        String name = data.get("name");
        String permission = data.get("permission");
        String description = data.get("description");
        roleMapper.insert(new Role(null,name,description,permission));
        map.put("message","success");
        return map;
    }

    @Override
    public Map<String, String> deleteRole(Map<String, String> data) {
        String role = data.get("role");
        String id = data.get("id");
        Map<String, String> map = new HashMap<>();
        if("ROLE_ADMIN".equals(role)){
            roleMapper.deleteById(id);
            map.put("message","success");
            return map;
        }
        map.put("message","error");
        return map;
    }

    @Override
    public Map<String, String> updateRole(Map<String, String> data) {
        Integer id = Integer.parseInt(data.get("id"));
        String name = data.get("name");
        String permission = data.get("permission");
        String description = data.get("description");
        String role = data.get("role");
        Map<String, String> map = new HashMap<>();
        Role roleEntity = new Role(id,name, description, permission);
        if("ROLE_ADMIN".equals(role)){
            roleMapper.updateById(roleEntity)   ;
            map.put("message","success");
            return map;
        }
        map.put("message","error");
        return map;
    }

    @Override
    public List<Menu> getMenuTree(Map<String, String> data) {
        String role = data.get("role");
        Integer roleId = Integer.parseInt(data.get("roleId"));
        if("ROLE_ADMIN".equals(role)){
            return menuService.getMenu(roleId);
        }
        return null;
    }
}
